package binaryTree;

import java.util.LinkedList;
import java.util.Queue;

/*
 *@description 填充每个节点的下一个右侧节点指针 II
 *@author hkfan
 *@version 1.0
 *@create 2025/6/16 15:36
 */
public class LeetCode_117 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };

    public Node connect(Node root) {
        //1. 定义
        Queue<Node> queue = new LinkedList<>();
        //2. 初始化
        queue.add(root);
        queue.add(null);
        //3. 循环
        while (!queue.isEmpty()){
            Node node = queue.poll();
            if (node==null){
                continue;
            }
            node.next=queue.peek();
            Boolean flag = false;
            if ((!queue.isEmpty())&& queue.peek()==null ){
                flag=true;
            }
            if (node.left!=null){
                queue.add(node.left);
            }
            if (node.right!=null){
                queue.add(node.right);
            }

            if (flag){
                queue.add(null);
            }
        }

        return root;
    }


}
